package br.com.academia.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.academia.dao.MatriculaDAO;
import br.com.academia.modelo.Matricula;

public class MatriculaAlterar extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public MatriculaAlterar() {
		super();
	}

	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();

		int id = Integer.parseInt(request.getParameter("id"));
		String nome = request.getParameter("nome").trim();
		String email = request.getParameter("email").trim();
		String nascimento = request.getParameter("nascimento").trim();
		String sexo;
		int cpf;
		int telefone;

		if (nome.equals("") || nascimento.equals("") || email.equals("")) {
			out.print("<script language='javascript'>");
			out.print("alert('Preencha todos os campos!');");
			out.print("history.back();");
			out.print("</script>");
			return;
		}

		try {
			sexo = request.getParameter("sexo").trim();
			cpf = Integer.parseInt(request.getParameter("cpf").trim());
			telefone = Integer
					.parseInt(request.getParameter("telefone").trim());
		} catch (Exception e) {
			out.print("<script language='javascript'>");
			out.print("alert('Os campos cpf e telefone sao numeros!');");
			out.print("history.back();");
			out.print("</script>");
			return;
		}

		Matricula matricula = new Matricula();
		matricula.setIdmatricula(id);
		matricula.setNome(nome);
		matricula.setCpf(cpf);
		matricula.setEmail(email);
		matricula.setNascimento(nascimento);
		matricula.setTelefone(telefone);
		matricula.setSexo(sexo);

		MatriculaDAO dao = new MatriculaDAO();

		out.print("<script language='javascript'>");
		if (dao.alterar(matricula)) {
			out.print("alert('Informacao Salva!');");
		} else {
			out.print("alert('Erro!');");
		}
		out.print("location.href='/academia/menu/pre-matricula-listar.jsp'");
		out.print("</script>");

	}

}
